package com.tool.tab;

import com.tool.btn.TitlelBtn;
import org.come.Jpanel.CustomTitleBarUI;
import org.come.bean.LoginResult;
import org.come.socket.GameClient;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TabJFrame extends JFrame {

    public CustomTitleBarUI customTitleBarUI;
    JSplitPane jSplitPane;
    JPanel add;
    JPanel addBTC;

    public JTabbedPane jTabbedPane = new JTabbedPane();
    public static int index = 0;
    public static int shouId = 0;
    public HashMap<Integer, Process> games = new HashMap<>();
    public HashMap<Integer, LoginResult> roles = new HashMap<>();
    private int jdNum = 100;
    public static Boolean start = false;

    public TabJFrame() {
        // 设置窗口不可调整大小
        setResizable(false);
        // 获取工具包
        Toolkit tool = this.getToolkit();
        // 获取图标图片
        Image myimage = tool.getImage("img/icon/ico.png");
        // 设置窗口图标
        this.setIconImage(myimage);
        // 创建自定义标题栏
        customTitleBarUI = new CustomTitleBarUI(this);
        // 设置标题
        customTitleBarUI.setTitle("大话西游经典版");
        // 将选项卡面板添加到窗口中心
        this.add(jTabbedPane, BorderLayout.CENTER);
        // 将自定义标题栏添加到窗口顶部
        this.add(customTitleBarUI, BorderLayout.NORTH);

        // 设置jTabbedPane为双缓冲
        jTabbedPane.setDoubleBuffered(true);
        // 设置jTabbedPane为透明
        jTabbedPane.setOpaque(false);
        // 设置jTabbedPane不可见
        jTabbedPane.setVisible(false);
        // 设置jTabbedPane的背景颜色为黄色
        jTabbedPane.setBackground(Color.yellow);
        // 创建内容
        add = createContent(-1);
        // 将内容添加到当前窗口
        this.add(add);
        // 创建一个新的ButtonTabComponent对象，并将其添加到jTabbedPane中
        addBTC = new ButtonTabComponent(jTabbedPane, false);
        // 在jTabbedPane中添加一个新的选项卡，选项卡标题为"  +  "
        jTabbedPane.add("  +  ", add);
        // 将addBTC设置为jTabbedPane的第一个选项卡的组件
        jTabbedPane.setTabComponentAt(0, addBTC);
//        // 设置jTabbedPane的尺寸为1016x768
//        jTabbedPane.setPreferredSize(new Dimension(1016, 768));
        // 设置jTabbedPane的位置和大小
        jTabbedPane.setBounds(6, 20, 1026, 78);
        // 设置jTabbedPane的边框为空
        jTabbedPane.setBorder(BorderFactory.createEmptyBorder());
//        // 设置jTabbedPane的边框为橙色
//        jTabbedPane.setBorder(BorderFactory.createLineBorder(Color.orange));
        // 调用addGame()方法，获取id
        int id = addGame();
        // 调用showGame()方法，显示id对应的游戏
        showGame(id);

        this.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {


            }

            @Override
            public void windowClosing(WindowEvent e) {

            }

            @Override
            public void windowClosed(WindowEvent e) {

            }

            @Override
            public void windowIconified(WindowEvent e) {
                Main.tabJFrame.games.forEach((k, v) -> {
                    Process process = Main.tabJFrame.games.get(k);

                    try {
                        process.getOutputStream().write(("chatHide" + "\n").getBytes());
                        process.getOutputStream().flush();
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
//                }
                });
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                // 遍历游戏列表
                Main.tabJFrame.games.forEach((k, v) -> {
                    // 获取游戏进程
                    Process process = Main.tabJFrame.games.get(k);
                    // 如果游戏ID等于shouId
                    if (k == shouId) {
                        // 向游戏进程发送chatShow命令
                        try {
                            process.getOutputStream().write(("chatShow" + "\n").getBytes());
                            process.getOutputStream().flush();
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    } else {
                        // 否则向游戏进程发送chatHide命令
                        try {
                            process.getOutputStream().write(("chatHide" + "\n").getBytes());
                            process.getOutputStream().flush();
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
//                }
                    }
                });
            }

            @Override
            public void windowActivated(WindowEvent e) {

            }

            @Override
            public void windowDeactivated(WindowEvent e) {

            }
        });
        // 隐藏选项卡
        jTabbedPane.setVisible(false);
//
        // 设置窗口无边框
        this.setUndecorated(true);
        // 设置窗口大小
        this.setPreferredSize(new Dimension(1026, 768));
        // 设置窗口标题
        this.setTitle(Main.title);
        // 窗口自适应
        this.pack();
        // 居中显示
        this.setLocationRelativeTo(null);
    }

    public int addGame() {
        ProcessBuilder processBuilder = getProcess(index);
        // 设置环境变量，改变输出编码为UTF-8
        Process process = null;
        try {
            process = processBuilder.start();
            Process finalProcess = process;
            int id = index;
            new Thread(() -> {
                int len;
                InputStream in = finalProcess.getInputStream();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in, Main.debug ? "UTF-8" : "GBK"));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("switch")) {
                            Integer index = Main.tabJFrame.shouId;
                            List<TitlelBtn> titlelBtns = customTitleBarUI.getTitlelBtns();
                            for (int i = 0; i < titlelBtns.size(); i++) {
                                if (titlelBtns.get(i).getCaozuo() == index) {
                                    if (i == titlelBtns.size() - 1) {
                                        // 如果是最后一个，将第一个按钮设置为不选中
                                        titlelBtns.get(0).nochoose(null);
                                        break;
                                    } else {
                                        // 将下一个按钮设置为不选中
                                        titlelBtns.get(i + 1).nochoose(null);
                                        break;
                                    }
                                }

                            }


                        }
                        // 如果当前行以"Rolename"开头
                        if (line.startsWith("Rolename")) {
                            // 以换行符分割字符串
                            String[] v = line.split("\n");
                            // 创建LoginResult对象
                            LoginResult loginResult = new LoginResult();
                            // 以等号分割字符串
                            v = v[0].split("=");
                            // 设置rolename
                            loginResult.setRolename(v[1]);
                            // 设置species_id
                            loginResult.setSpecies_id(new BigDecimal(v[2]));
                            // 设置race_name
                            loginResult.setRace_name(v[4]);
                            // 设置role_id
                            loginResult.setRole_id(new BigDecimal(v[5]));
                            // 设置BT
                            loginResult.setBT(v[6]);
                            // 获取int类型的v[3]
                            int i = Integer.parseInt(v[3]);
                            // 将loginResult对象放入Main.tabJFrame.roles中
                            Main.tabJFrame.roles.put(i, loginResult);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();

            new Thread(() -> {
                int len;
                try {
                    // 获取进程的错误流
                    InputStream in1 = finalProcess.getErrorStream();
                    // 循环读取错误流中的数据
                    for (byte[] bytes = new byte[1024]; (len = in1.read(bytes)) > 0; ) {
                        // 将字节数组转换为字符串
                        String str = new String(bytes, 0, len);
                        // 输出错误流中的数据
                        System.out.println(str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
//        jTabbedPane.remove(index);
        // 向games中添加一个键值对，key为index，value为process
        games.put(index, process);
        // 创建一个JPanel，名为tab
        JPanel tab = createContent(index);
        // 创建一个ButtonTabComponent，名为btc，参数为jTabbedPane和true
        ButtonTabComponent btc = new ButtonTabComponent(jTabbedPane, true);
        // 向jTabbedPane中添加一个tab，参数为tab、GameClient.BT和index
        jTabbedPane.add(tab, GameClient.BT, index);
        // 向jTabbedPane中添加一个"+"，参数为add、"+"和index+1
        jTabbedPane.add(add, "+", index + 1);
        // 向jTabbedPane中设置btc为第index个标签的组件
        jTabbedPane.setTabComponentAt(index, btc);
        // 向jTabbedPane中设置addBTC为第index+1个标签的组件
        jTabbedPane.setTabComponentAt(index + 1, addBTC);
        // 如果Main.tabJFrame不为空，则将customTitleBarUI设置为第一层
        if (Main.tabJFrame != null) {
            Main.tabJFrame.setComponentZOrder(customTitleBarUI, 1);
        }
        // 刷新customTitleBarUI中的角色
        //        customTitleBarUI.refreshRoles();
        // 返回index自增后的值
        return index++;
    }


    // 移除指定id的游戏
    public void removeGame(int id) {
        // 设置指定id的标签组件为空
        jTabbedPane.setTabComponentAt(id, new JLabel());
    }

    // 显示指定id的游戏
    public void showGame(int id) {
        // 将lastX和lastY设置为-1
        Main.lastX = -1;
        Main.lastY = -1;
        // 将shouId设置为指定id
        shouId = id;
    }

    public JSplitPane getJSplitPane() {
        return jSplitPane;
    }

    public HashMap<Integer, Process> getGames() {
        return games;
    }

    public int getShouId() {
        return shouId;
    }

    public ProcessBuilder getProcess(int id) {

        List<String> res = new ArrayList<>();
        if (Main.debug) {
            String b = "jre\\";
            String subStringB = b.substring(b.lastIndexOf("/") + 1);
            int index = subStringB.lastIndexOf("\\");
            String pa = subStringB.substring(0, index) + "\\bin\\java.exe";
            pa = pa.replaceAll("\\\\", "\\\\\\\\");
            res.add(pa);
            res.add("-Dfile.encoding=UTF-8");
            res.add("-classpath");
            res.add("\"" + Main.dir + "\\out\\production\\GameClient;" +
                    Main.dir + "\\jre\\lib\\charsets.jar;" +
                    Main.dir + "\\jre\\lib\\deploy.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\access-bridge-64.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\cldrdata.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\dnsns.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\jaccess.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\jfxrt.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\localedata.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\nashorn.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\sunec.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\sunjce_provider.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\sunmscapi.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\sunpkcs11.jar;" +
                    Main.dir + "\\jre\\lib\\ext\\zipfs.jar;" +
                    Main.dir + "\\jre\\lib\\javaws.jar;" +
                    Main.dir + "\\jre\\lib\\jce.jar;" +
                    Main.dir + "\\jre\\lib\\jfr.jar;" +
                    Main.dir + "\\jre\\lib\\jfxswt.jar;" +
                    Main.dir + "\\jre\\lib\\jsse.jar;" +
                    Main.dir + "\\jre\\lib\\management-agent.jar;" +
                    Main.dir + "\\jre\\lib\\plugin.jar;" +
                    Main.dir + "\\jre\\lib\\resources.jar;" +
                    Main.dir + "\\jre\\lib\\rt.jar;" +
                    Main.dir + "\\jre\\lib\\security\\policy\\limited\\local_policy.jar;" +
                    Main.dir + "\\jre\\lib\\security\\policy\\limited\\US_export_policy.jar;" +
                    Main.dir + "\\jre\\lib\\security\\policy\\unlimited\\local_policy.jar;" +
                    Main.dir + "\\jre\\lib\\security\\policy\\unlimited\\US_export_policy.jar;" +
                    Main.dir + "\\libs\\commons-beanutils-1.8.0.jar;" +
                    Main.dir + "\\libs\\commons-beanutils-core-1.8.2.jar;" +
                    Main.dir + "\\libs\\commons-codec-1.3.jar;" +
                    Main.dir + "\\libs\\commons-collections-3.2.1.jar;" +
                    Main.dir + "\\libs\\commons-dbutils-1.3.jar;" +
                    Main.dir + "\\libs\\commons-httpclient-3.0-rc4.jar;" +
                    Main.dir + "\\libs\\commons-jexl-2.0.1.jar;" +
                    Main.dir + "\\libs\\commons-lang-2.6.jar;" +
                    Main.dir + "\\libs\\hutool-all-5.8.5.jar;" +
                    Main.dir + "\\libs\\commons-logging-1.0.4.jar;" +
                    Main.dir + "\\libs\\commons-logging-1.1.1.jar;" +
                    Main.dir + "\\libs\\dom4j-1.6.1.jar;" +
                    Main.dir + "\\libs\\gson-2.2.4.jar;" +
                    Main.dir + "\\libs\\mp3spi1.9.5.jar;" +
                    Main.dir + "\\libs\\netty-all-4.1.19.Final-sources.jar;" +
                    Main.dir + "\\libs\\netty-all-4.1.19.Final.jar;" +
                    Main.dir + "\\libs\\tritonus_share.jar;" +
                    Main.dir + "\\libs\\poi-1.8.0-dev-20020919.jar;" +
                    Main.dir + "\\libs\\poi-3.9.20130515.jar;" +
                    Main.dir + "\\libs\\ImageEditor.jar;" +
                    Main.dir + "\\libs\\spark-excel_2.12-0.11.5.jar;" +
                    Main.dir + "\\libs\\slf4j-jdk14-1.7.13.jar;" +
                    Main.dir + "\\libs\\tritonus_share.jar;" +
                    Main.dir + "\\libs\\mp3spi1.9.5.jar;" +
                    Main.dir + "\\libs\\ImageEditor.jar;" +
                    Main.dir + "\\libs\\json.jar;" +
                    Main.dir + "\\libs\\commons-io-1.4.jar;\"");
            //添加org.come.test.Main到res集合中
            res.add("org.come.test.Main");
            //如果com.tool.tab.Main.tabName为空，则将其设置为当前系统时间的字符串形式
            if (Main.tabName == null)
                Main.tabName = System.currentTimeMillis() + "";
            //将-name=com.tool.tab.Main.tabName添加到res集合中
            res.add("-name=" + Main.tabName);
            //将-index=id添加到res集合中
            res.add("-index=" + id);
            //将-Dfile.encoding=UTF-8添加到res集合中
            res.add("-Dfile.encoding=UTF-8");
        } else {
            res.add("launcher.exe");//修改客户端exe名字
            if (Main.tabName == null)
                Main.tabName = System.currentTimeMillis() + "";
            res.add("-name=" + Main.tabName);
            res.add("-index=" + id);

        }
        //创建ProcessBuilder对象，参数为res集合
        ProcessBuilder processBuilder = new ProcessBuilder(res);
        //注释掉processBuilder.inheritIO();
//        processBuilder.inheritIO();
        //设置processBuilder的工作目录为com.tool.tab.Main.dir + \
        processBuilder.directory(new File(Main.dir + "\\"));
        //返回processBuilder
        return processBuilder;
    }

    public JPanel createContent(int id) {
        // 创建一个JPanel对象
        // 返回JPanel对象
        return new JPanel() {
            // 重写setVisible方法
            @Override
            public void setVisible(boolean aFlag) {
                // 如果aFlag的值和当前面板的可见性相同，则直接返回
                if (aFlag == isVisible()) return;
                // 调用父类的setVisible方法，设置面板的可见性
                super.setVisible(aFlag);
                // 如果面板可见性为true
                if (aFlag) {
                    // 如果id大于等于0
                    if (id >= 0) {
                        // 如果TabJFrame的shouId不等于id，则调用showGame方法
                        if (TabJFrame.shouId != id) showGame(id);
                    } else {
                        // 如果index大于0且没有正在添加游戏，则调用addGame方法
                        if (index > 0 && !Main.addIng) {
                            int ii = TabJFrame.shouId;
                            Main.addIng = true;
//                            addGame();
                            // 设置当前面板为选中面板
                            jTabbedPane.setSelectedIndex(ii);
                            Main.addIng = false;
                        }
                    }
                }
            }


        };

    }


    public static void setShouId(int shouId) {
        TabJFrame.shouId = shouId;
    }

    public static void setIndex(int index) {
        TabJFrame.index = index;
    }




    public CustomTitleBarUI getCustomTitleBarUI() {
        return customTitleBarUI;
    }

    public void setCustomTitleBarUI(CustomTitleBarUI customTitleBarUI) {
        this.customTitleBarUI = customTitleBarUI;
    }
}
